package common.security.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

public class SavedRequestAwareAuthenticationSuccessHandler extends
		org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler {
	private String defaultAdminTargetUrl;
	private String ajaxTargetUrl;
	private RequestCache requestCache = new HttpSessionRequestCache();

	public String getDefaultAdminTargetUrl() {
		return defaultAdminTargetUrl;
	}

	public void setDefaultAdminTargetUrl(String defaultAdminTargetUrl) {
		this.defaultAdminTargetUrl = defaultAdminTargetUrl;
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		SavedRequest savedRequest = requestCache.getRequest(request, response);

		String targetUrlParameter = getTargetUrlParameter();
		String defaultTargetUrl = getDefaultTargetUrl();
		if ("true".equals(request.getParameter("isAdmin"))) {
			defaultTargetUrl = getDefaultAdminTargetUrl();
		}

		boolean isAjax = false;
		// 如果是ajax请求
		if (org.apache.commons.lang3.StringUtils.isNotBlank(request.getHeader("Accept")) && request.getHeader("Accept").contains("application/json")) {
			defaultTargetUrl = getAjaxTargetUrl();
			targetUrlParameter = null;
			isAjax = true;
		}
		if (isAlwaysUseDefaultTargetUrl()
				|| (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
			requestCache.removeRequest(request, response);
			super.onAuthenticationSuccess(request, response, authentication);
			return;
		}
		
		if (savedRequest == null || isAjax) {
			getRedirectStrategy().sendRedirect(request, response, defaultTargetUrl);
			return;
		}
		
		clearAuthenticationAttributes(request);

		// Use the DefaultSavedRequest URL
		String targetUrl = savedRequest.getRedirectUrl();
		logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
		getRedirectStrategy().sendRedirect(request, response, targetUrl);
	}

	public void setRequestCache(RequestCache requestCache) {
		this.requestCache = requestCache;
	}

	public String getAjaxTargetUrl() {
		return ajaxTargetUrl;
	}

	public void setAjaxTargetUrl(String ajaxTargetUrl) {
		this.ajaxTargetUrl = ajaxTargetUrl;
	}


}
